import React, { useMemo, useState } from 'react'
import { Card, Grid, AutoCenter, DatePicker } from 'antd-mobile'
import DayBillList from './Components/DayBillList'
import { useSelector } from 'react-redux'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faAngleDown } from '@fortawesome/free-solid-svg-icons'
import { NavBar } from 'antd-mobile'
import dayjs from 'dayjs'
import _ from 'lodash'

const Month = () => {
	const [visible, setVisible] = useState(false)

	const billsList = useSelector(state => state.bills.billsList)

	const monthGroup = useMemo(() => {
		return _.groupBy(billsList, item =>
			dayjs(item.date).format('YYYY-MM')
		)
	}, [billsList])

	const [currentDate, setCurrentDate] = useState(() => {
		return dayjs(new Date()).format('YYYY-MM')
	})

	const [currentMonthBills, setCurrentMonthBills] = useState(monthGroup[currentDate] || [])

	console.log(currentMonthBills);
	const monthResult = useMemo(() => {
		const pay = currentMonthBills.filter(item => item.type === 'pay').reduce((acc, cur) => acc + cur.money, 0)
		const income = currentMonthBills.filter(item => item.type === 'income').reduce((acc, cur) => acc + cur.money, 0)
		return {
			pay,
			income,
			total: (income - pay).toFixed(2)
		}
	}, [currentMonthBills])

	return (
		<>
			<header>
				<NavBar
					style={{
						'--height': '36px',
						backgroundColor: '#fff',
					}}
					backIcon={null}
				>
					Month Bill
				</NavBar>
			</header>
			<section style={{ margin: '10px' }}>
				<Card title={
					<div>
						<span>
							{currentDate} Bill
						</span>
						<FontAwesomeIcon icon={faAngleDown} onClick={() => { setVisible(true) }} />
					</div>
				}>
					<Grid columns={3}>
						<Grid columns={1}>
							<Grid.Item>
								<AutoCenter>{monthResult.income}</AutoCenter>
							</Grid.Item>
							<Grid.Item>
								<AutoCenter style={{ fontWeight: 'bold' }}>pay</AutoCenter>
							</Grid.Item>
						</Grid>
						<Grid columns={1}>
							<Grid.Item>
								<AutoCenter>{monthResult.pay}</AutoCenter>
							</Grid.Item>
							<Grid.Item>
								<AutoCenter style={{ fontWeight: 'bold' }}>income</AutoCenter>
							</Grid.Item>
						</Grid>
						<Grid columns={1}>
							<Grid.Item>
								<AutoCenter>{monthResult.total}</AutoCenter>
							</Grid.Item>
							<Grid.Item>
								<AutoCenter style={{ fontWeight: 'bold' }}>balances</AutoCenter>
							</Grid.Item>
						</Grid>
					</Grid>
				</Card>
				<DatePicker
					visible={visible}
					onClose={() => {
						setVisible(false)
					}}
					precision='month'
					onConfirm={(date) => {
						setVisible(false)
						const formattedDate = dayjs(date).format('YYYY-MM')
						setCurrentDate(formattedDate)
						setCurrentMonthBills(monthGroup[formattedDate] || [])
					}}
					cancelText='Cancel'
					confirmText='Confirm'
				/>

				<DayBillList currentMonthBills={currentMonthBills} />

			</section >
		</>
	)
}

export default Month